home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / email / message.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  28KB  |  783 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Basic message object for the email package object model.'''
  5. __all__ = [
  6.     'Message']
  7. import re
  8. import uu
  9. import binascii
  10. import warnings
  11. from cStringIO import StringIO
  12. import email.charset as email
  13. from email import utils
  14. from email import errors
  15. SEMISPACE = '; '
  16. tspecials = re.compile('[ \\(\\)<>@,;:\\\\"/\\[\\]\\?=]')
  17.  
  18. def _splitparam(param):
  19.     (a, sep, b) = param.partition(';')
  20.     if not sep:
  21.         return (a.strip(), None)
  22.     return (a.strip(), b.strip())
  23.  
  24.  
  25. def _formatparam(param, value = None, quote = True):
  26.     '''Convenience function to format and return a key=value pair.
  27.  
  28.     This will quote the value if needed or if quote is true.
  29.     '''
  30.     if value is not None and len(value) > 0:
  31.         if isinstance(value, tuple):
  32.             param += '*'
  33.             value = utils.encode_rfc2231(value[2], value[0], value[1])
  34.         
  35.         if quote or tspecials.search(value):
  36.             return '%s="%s"' % (param, utils.quote(value))
  37.         return '%s=%s' % (param, value)
  38.     len(value) > 0
  39.     return param
  40.  
  41.  
  42. def _parseparam(s):
  43.     plist = []
  44.     while s[:1] == ';':
  45.         s = s[1:]
  46.         end = s.find(';')
  47.         while end > 0 and s.count('"', 0, end) % 2:
  48.             end = s.find(';', end + 1)
  49.         if end < 0:
  50.             end = len(s)
  51.         
  52.         f = s[:end]
  53.         if '=' in f:
  54.             i = f.index('=')
  55.             f = f[:i].strip().lower() + '=' + f[i + 1:].strip()
  56.         
  57.         plist.append(f.strip())
  58.         s = s[end:]
  59.     return plist
  60.  
  61.  
  62. def _unquotevalue(value):
  63.     if isinstance(value, tuple):
  64.         return (value[0], value[1], utils.unquote(value[2]))
  65.     return utils.unquote(value)
  66.  
  67.  
  68. class Message:
  69.     """Basic message object.
  70.  
  71.     A message object is defined as something that has a bunch of RFC 2822
  72.     headers and a payload.  It may optionally have an envelope header
  73.     (a.k.a. Unix-From or From_ header).  If the message is a container (i.e. a
  74.     multipart or a message/rfc822), then the payload is a list of Message
  75.     objects, otherwise it is a string.
  76.  
  77.     Message objects implement part of the `mapping' interface, which assumes
  78.     there is exactly one occurrance of the header per message.  Some headers
  79.     do in fact appear multiple times (e.g. Received) and for those headers,
  80.     you must use the explicit API to set or get all the headers.  Not all of
  81.     the mapping methods are implemented.
  82.     """
  83.     
  84.     def __init__(self):
  85.         self._headers = []
  86.         self._unixfrom = None
  87.         self._payload = None
  88.         self._charset = None
  89.         self.preamble = None
  90.         self.epilogue = None
  91.         self.defects = []
  92.         self._default_type = 'text/plain'
  93.  
  94.     
  95.     def __str__(self):
  96.         '''Return the entire formatted message as a string.
  97.         This includes the headers, body, and envelope header.
  98.         '''
  99.         return self.as_string(unixfrom = True)
  100.  
  101.     
  102.     def as_string(self, unixfrom = False):
  103.         '''Return the entire formatted message as a string.
  104.         Optional `unixfrom\' when True, means include the Unix From_ envelope
  105.         header.
  106.  
  107.         This is a convenience method and may not generate the message exactly
  108.         as you intend because by default it mangles lines that begin with
  109.         "From ".  For more flexibility, use the flatten() method of a
  110.         Generator instance.
  111.         '''
  112.         Generator = Generator
  113.         import email.generator
  114.         fp = StringIO()
  115.         g = Generator(fp)
  116.         g.flatten(self, unixfrom = unixfrom)
  117.         return fp.getvalue()
  118.  
  119.     
  120.     def is_multipart(self):
  121.         '''Return True if the message consists of multiple parts.'''
  122.         return isinstance(self._payload, list)
  123.  
  124.     
  125.     def set_unixfrom(self, unixfrom):
  126.         self._unixfrom = unixfrom
  127.  
  128.     
  129.     def get_unixfrom(self):
  130.         return self._unixfrom
  131.  
  132.     
  133.     def attach(self, payload):
  134.         '''Add the given payload to the current payload.
  135.  
  136.         The current payload will always be a list of objects after this method
  137.         is called.  If you want to set the payload to a scalar object, use
  138.         set_payload() instead.
  139.         '''
  140.         if self._payload is None:
  141.             self._payload = [
  142.                 payload]
  143.         else:
  144.             self._payload.append(payload)
  145.  
  146.     
  147.     def get_payload(self, i = None, decode = False):
  148.         """Return a reference to the payload.
  149.  
  150.         The payload will either be a list object or a string.  If you mutate
  151.         the list object, you modify the message's payload in place.  Optional
  152.         i returns that index into the payload.
  153.  
  154.         Optional decode is a flag indicating whether the payload should be
  155.         decoded or not, according to the Content-Transfer-Encoding header
  156.         (default is False).
  157.  
  158.         When True and the message is not a multipart, the payload will be
  159.         decoded if this header's value is `quoted-printable' or `base64'.  If
  160.         some other encoding is used, or the header is missing, or if the
  161.         payload has bogus data (i.e. bogus base64 or uuencoded data), the
  162.         payload is returned as-is.
  163.  
  164.         If the message is a multipart and the decode flag is True, then None
  165.         is returned.
  166.         """
  167.         if i is None:
  168.             payload = self._payload
  169.         elif not isinstance(self._payload, list):
  170.             raise TypeError('Expected list, got %s' % type(self._payload))
  171.         else:
  172.             payload = self._payload[i]
  173.         return payload
  174.  
  175.     
  176.     def set_payload(self, payload, charset = None):
  177.         """Set the payload to the given value.
  178.  
  179.         Optional charset sets the message's default character set.  See
  180.         set_charset() for details.
  181.         """
  182.         self._payload = payload
  183.         if charset is not None:
  184.             self.set_charset(charset)
  185.         
  186.  
  187.     
  188.     def set_charset(self, charset):
  189.         '''Set the charset of the payload to a given character set.
  190.  
  191.         charset can be a Charset instance, a string naming a character set, or
  192.         None.  If it is a string it will be converted to a Charset instance.
  193.         If charset is None, the charset parameter will be removed from the
  194.         Content-Type field.  Anything else will generate a TypeError.
  195.  
  196.         The message will be assumed to be of type text/* encoded with
  197.         charset.input_charset.  It will be converted to charset.output_charset
  198.         and encoded properly, if needed, when generating the plain text
  199.         representation of the message.  MIME headers (MIME-Version,
  200.         Content-Type, Content-Transfer-Encoding) will be added as needed.
  201.  
  202.         '''
  203.         if charset is None:
  204.             self.del_param('charset')
  205.             self._charset = None
  206.             return None
  207.         if isinstance(charset, basestring):
  208.             charset = email.charset.Charset(charset)
  209.         
  210.         if not isinstance(charset, email.charset.Charset):
  211.             raise TypeError(charset)
  212.         isinstance(charset, email.charset.Charset)
  213.         self._charset = charset
  214.         if not self.has_key('MIME-Version'):
  215.             self.add_header('MIME-Version', '1.0')
  216.         
  217.         if not self.has_key('Content-Type'):
  218.             self.add_header('Content-Type', 'text/plain', charset = charset.get_output_charset())
  219.         else:
  220.             self.set_param('charset', charset.get_output_charset())
  221.         if str(charset) != charset.get_output_charset():
  222.             self._payload = charset.body_encode(self._payload)
  223.         
  224.         if not self.has_key('Content-Transfer-Encoding'):
  225.             cte = charset.get_body_encoding()
  226.             
  227.             try:
  228.                 cte(self)
  229.             except TypeError:
  230.                 self._payload = charset.body_encode(self._payload)
  231.                 self.add_header('Content-Transfer-Encoding', cte)
  232.             except:
  233.                 None<EXCEPTION MATCH>TypeError
  234.             
  235.  
  236.         None<EXCEPTION MATCH>TypeError
  237.  
  238.     
  239.     def get_charset(self):
  240.         """Return the Charset instance associated with the message's payload.
  241.         """
  242.         return self._charset
  243.  
  244.     
  245.     def __len__(self):
  246.         '''Return the total number of headers, including duplicates.'''
  247.         return len(self._headers)
  248.  
  249.     
  250.     def __getitem__(self, name):
  251.         '''Get a header value.
  252.  
  253.         Return None if the header is missing instead of raising an exception.
  254.  
  255.         Note that if the header appeared multiple times, exactly which
  256.         occurrance gets returned is undefined.  Use get_all() to get all
  257.         the values matching a header field name.
  258.         '''
  259.         return self.get(name)
  260.  
  261.     
  262.     def __setitem__(self, name, val):
  263.         '''Set the value of a header.
  264.  
  265.         Note: this does not overwrite an existing header with the same field
  266.         name.  Use __delitem__() first to delete any existing headers.
  267.         '''
  268.         self._headers.append((name, val))
  269.  
  270.     
  271.     def __delitem__(self, name):
  272.         '''Delete all occurrences of a header, if present.
  273.  
  274.         Does not raise an exception if the header is missing.
  275.         '''
  276.         name = name.lower()
  277.         newheaders = []
  278.         for k, v in self._headers:
  279.             if k.lower() != name:
  280.                 newheaders.append((k, v))
  281.                 continue
  282.         
  283.         self._headers = newheaders
  284.  
  285.     
  286.     def __contains__(self, name):
  287.         return [] in [ k.lower() for k, v in self._headers ]
  288.  
  289.     
  290.     def has_key(self, name):
  291.         '''Return true if the message contains the header.'''
  292.         missing = object()
  293.         return self.get(name, missing) is not missing
  294.  
  295.     
  296.     def keys(self):
  297.         """Return a list of all the message's header field names.
  298.  
  299.         These will be sorted in the order they appeared in the original
  300.         message, or were added to the message, and may contain duplicates.
  301.         Any fields deleted and re-inserted are always appended to the header
  302.         list.
  303.         """
  304.         return [ k for k, v in self._headers ]
  305.  
  306.     
  307.     def values(self):
  308.         """Return a list of all the message's header values.
  309.  
  310.         These will be sorted in the order they appeared in the original
  311.         message, or were added to the message, and may contain duplicates.
  312.         Any fields deleted and re-inserted are always appended to the header
  313.         list.
  314.         """
  315.         return [ v for k, v in self._headers ]
  316.  
  317.     
  318.     def items(self):
  319.         """Get all the message's header fields and values.
  320.  
  321.         These will be sorted in the order they appeared in the original
  322.         message, or were added to the message, and may contain duplicates.
  323.         Any fields deleted and re-inserted are always appended to the header
  324.         list.
  325.         """
  326.         return self._headers[:]
  327.  
  328.     
  329.     def get(self, name, failobj = None):
  330.         '''Get a header value.
  331.  
  332.         Like __getitem__() but return failobj instead of None when the field
  333.         is missing.
  334.         '''
  335.         name = name.lower()
  336.         for k, v in self._headers:
  337.             if k.lower() == name:
  338.                 return v
  339.         
  340.         return failobj
  341.  
  342.     
  343.     def get_all(self, name, failobj = None):
  344.         '''Return a list of all the values for the named field.
  345.  
  346.         These will be sorted in the order they appeared in the original
  347.         message, and may contain duplicates.  Any fields deleted and
  348.         re-inserted are always appended to the header list.
  349.  
  350.         If no such fields exist, failobj is returned (defaults to None).
  351.         '''
  352.         values = []
  353.         name = name.lower()
  354.         for k, v in self._headers:
  355.             if k.lower() == name:
  356.                 values.append(v)
  357.                 continue
  358.         
  359.         if not values:
  360.             return failobj
  361.         return values
  362.  
  363.     
  364.     def add_header(self, _name, _value, **_params):
  365.         '''Extended header setting.
  366.  
  367.         name is the header field to add.  keyword arguments can be used to set
  368.         additional parameters for the header field, with underscores converted
  369.         to dashes.  Normally the parameter will be added as key="value" unless
  370.         value is None, in which case only the key will be added.
  371.  
  372.         Example:
  373.  
  374.         msg.add_header(\'content-disposition\', \'attachment\', filename=\'bud.gif\')
  375.         '''
  376.         parts = []
  377.         for k, v in _params.items():
  378.             if v is None:
  379.                 parts.append(k.replace('_', '-'))
  380.                 continue
  381.             parts.append(_formatparam(k.replace('_', '-'), v))
  382.         
  383.         if _value is not None:
  384.             parts.insert(0, _value)
  385.         
  386.         self._headers.append((_name, SEMISPACE.join(parts)))
  387.  
  388.     
  389.     def replace_header(self, _name, _value):
  390.         '''Replace a header.
  391.  
  392.         Replace the first matching header found in the message, retaining
  393.         header order and case.  If no matching header was found, a KeyError is
  394.         raised.
  395.         '''
  396.         _name = _name.lower()
  397.         for k, v in zip(range(len(self._headers)), self._headers):
  398.             if k.lower() == _name:
  399.                 self._headers[i] = (k, _value)
  400.                 break
  401.                 continue
  402.         else:
  403.             raise KeyError(_name)
  404.  
  405.     
  406.     def get_content_type(self):
  407.         """Return the message's content type.
  408.  
  409.         The returned string is coerced to lower case of the form
  410.         `maintype/subtype'.  If there was no Content-Type header in the
  411.         message, the default type as given by get_default_type() will be
  412.         returned.  Since according to RFC 2045, messages always have a default
  413.         type this will always return a value.
  414.  
  415.         RFC 2045 defines a message's default type to be text/plain unless it
  416.         appears inside a multipart/digest container, in which case it would be
  417.         message/rfc822.
  418.         """
  419.         missing = object()
  420.         value = self.get('content-type', missing)
  421.         if value is missing:
  422.             return self.get_default_type()
  423.         ctype = _splitparam(value)[0].lower()
  424.         if ctype.count('/') != 1:
  425.             return 'text/plain'
  426.         return ctype
  427.  
  428.     
  429.     def get_content_maintype(self):
  430.         """Return the message's main content type.
  431.  
  432.         This is the `maintype' part of the string returned by
  433.         get_content_type().
  434.         """
  435.         ctype = self.get_content_type()
  436.         return ctype.split('/')[0]
  437.  
  438.     
  439.     def get_content_subtype(self):
  440.         """Returns the message's sub-content type.
  441.  
  442.         This is the `subtype' part of the string returned by
  443.         get_content_type().
  444.         """
  445.         ctype = self.get_content_type()
  446.         return ctype.split('/')[1]
  447.  
  448.     
  449.     def get_default_type(self):
  450.         """Return the `default' content type.
  451.  
  452.         Most messages have a default content type of text/plain, except for
  453.         messages that are subparts of multipart/digest containers.  Such
  454.         subparts have a default content type of message/rfc822.
  455.         """
  456.         return self._default_type
  457.  
  458.     
  459.     def set_default_type(self, ctype):
  460.         '''Set the `default\' content type.
  461.  
  462.         ctype should be either "text/plain" or "message/rfc822", although this
  463.         is not enforced.  The default content type is not stored in the
  464.         Content-Type header.
  465.         '''
  466.         self._default_type = ctype
  467.  
  468.     
  469.     def _get_params_preserve(self, failobj, header):
  470.         missing = object()
  471.         value = self.get(header, missing)
  472.         if value is missing:
  473.             return failobj
  474.         params = []
  475.         for p in _parseparam(';' + value):
  476.             
  477.             try:
  478.                 (name, val) = p.split('=', 1)
  479.                 name = name.strip()
  480.                 val = val.strip()
  481.             except ValueError:
  482.                 value is missing
  483.                 value is missing
  484.                 name = p.strip()
  485.                 val = ''
  486.             except:
  487.                 value is missing
  488.  
  489.             params.append((name, val))
  490.         
  491.         params = utils.decode_params(params)
  492.         return params
  493.  
  494.     
  495.     def get_params(self, failobj = None, header = 'content-type', unquote = True):
  496.         """Return the message's Content-Type parameters, as a list.
  497.  
  498.         The elements of the returned list are 2-tuples of key/value pairs, as
  499.         split on the `=' sign.  The left hand side of the `=' is the key,
  500.         while the right hand side is the value.  If there is no `=' sign in
  501.         the parameter the value is the empty string.  The value is as
  502.         described in the get_param() method.
  503.  
  504.         Optional failobj is the object to return if there is no Content-Type
  505.         header.  Optional header is the header to search instead of
  506.         Content-Type.  If unquote is True, the value is unquoted.
  507.         """
  508.         missing = object()
  509.         params = self._get_params_preserve(missing, header)
  510.         if params is missing:
  511.             return failobj
  512.         if unquote:
  513.             return [ (k, _unquotevalue(v)) for k, v in params ]
  514.         return params
  515.  
  516.     
  517.     def get_param(self, param, failobj = None, header = 'content-type', unquote = True):
  518.         """Return the parameter value if found in the Content-Type header.
  519.  
  520.         Optional failobj is the object to return if there is no Content-Type
  521.         header, or the Content-Type header has no such parameter.  Optional
  522.         header is the header to search instead of Content-Type.
  523.  
  524.         Parameter keys are always compared case insensitively.  The return
  525.         value can either be a string, or a 3-tuple if the parameter was RFC
  526.         2231 encoded.  When it's a 3-tuple, the elements of the value are of
  527.         the form (CHARSET, LANGUAGE, VALUE).  Note that both CHARSET and
  528.         LANGUAGE can be None, in which case you should consider VALUE to be
  529.         encoded in the us-ascii charset.  You can usually ignore LANGUAGE.
  530.  
  531.         Your application should be prepared to deal with 3-tuple return
  532.         values, and can convert the parameter to a Unicode string like so:
  533.  
  534.             param = msg.get_param('foo')
  535.             if isinstance(param, tuple):
  536.                 param = unicode(param[2], param[0] or 'us-ascii')
  537.  
  538.         In any case, the parameter value (either the returned string, or the
  539.         VALUE item in the 3-tuple) is always unquoted, unless unquote is set
  540.         to False.
  541.         """
  542.         if not self.has_key(header):
  543.             return failobj
  544.         for k, v in self._get_params_preserve(failobj, header):
  545.             if k.lower() == param.lower():
  546.                 if unquote:
  547.                     return _unquotevalue(v)
  548.                 return v
  549.             k.lower() == param.lower()
  550.         
  551.         return failobj
  552.  
  553.     
  554.     def set_param(self, param, value, header = 'Content-Type', requote = True, charset = None, language = ''):
  555.         '''Set a parameter in the Content-Type header.
  556.  
  557.         If the parameter already exists in the header, its value will be
  558.         replaced with the new value.
  559.  
  560.         If header is Content-Type and has not yet been defined for this
  561.         message, it will be set to "text/plain" and the new parameter and
  562.         value will be appended as per RFC 2045.
  563.  
  564.         An alternate header can specified in the header argument, and all
  565.         parameters will be quoted as necessary unless requote is False.
  566.  
  567.         If charset is specified, the parameter will be encoded according to RFC
  568.         2231.  Optional language specifies the RFC 2231 language, defaulting
  569.         to the empty string.  Both charset and language should be strings.
  570.         '''
  571.         if not isinstance(value, tuple) and charset:
  572.             value = (charset, language, value)
  573.         
  574.         if not self.has_key(header) and header.lower() == 'content-type':
  575.             ctype = 'text/plain'
  576.         else:
  577.             ctype = self.get(header)
  578.         if not self.get_param(param, header = header):
  579.             if not ctype:
  580.                 ctype = _formatparam(param, value, requote)
  581.             else:
  582.                 ctype = SEMISPACE.join([
  583.                     ctype,
  584.                     _formatparam(param, value, requote)])
  585.         else:
  586.             ctype = ''
  587.             for old_param, old_value in self.get_params(header = header, unquote = requote):
  588.                 append_param = ''
  589.                 if old_param.lower() == param.lower():
  590.                     append_param = _formatparam(param, value, requote)
  591.                 else:
  592.                     append_param = _formatparam(old_param, old_value, requote)
  593.                 if not ctype:
  594.                     ctype = append_param
  595.                     continue
  596.                 ctype = SEMISPACE.join([
  597.                     ctype,
  598.                     append_param])
  599.             
  600.         if ctype != self.get(header):
  601.             del self[header]
  602.             self[header] = ctype
  603.         
  604.  
  605.     
  606.     def del_param(self, param, header = 'content-type', requote = True):
  607.         '''Remove the given parameter completely from the Content-Type header.
  608.  
  609.         The header will be re-written in place without the parameter or its
  610.         value. All values will be quoted as necessary unless requote is
  611.         False.  Optional header specifies an alternative to the Content-Type
  612.         header.
  613.         '''
  614.         if not self.has_key(header):
  615.             return None
  616.         new_ctype = ''
  617.         for p, v in self.get_params(header = header, unquote = requote):
  618.             if p.lower() != param.lower():
  619.                 if not new_ctype:
  620.                     new_ctype = _formatparam(p, v, requote)
  621.                 else:
  622.                     new_ctype = SEMISPACE.join([
  623.                         new_ctype,
  624.                         _formatparam(p, v, requote)])
  625.             new_ctype
  626.         
  627.         if new_ctype != self.get(header):
  628.             del self[header]
  629.             self[header] = new_ctype
  630.         
  631.  
  632.     
  633.     def set_type(self, type, header = 'Content-Type', requote = True):
  634.         '''Set the main type and subtype for the Content-Type header.
  635.  
  636.         type must be a string in the form "maintype/subtype", otherwise a
  637.         ValueError is raised.
  638.  
  639.         This method replaces the Content-Type header, keeping all the
  640.         parameters in place.  If requote is False, this leaves the existing
  641.         header\'s quoting as is.  Otherwise, the parameters will be quoted (the
  642.         default).
  643.  
  644.         An alternative header can be specified in the header argument.  When
  645.         the Content-Type header is set, we\'ll always also add a MIME-Version
  646.         header.
  647.         '''
  648.         if not type.count('/') == 1:
  649.             raise ValueError
  650.         type.count('/') == 1
  651.         if header.lower() == 'content-type':
  652.             del self['mime-version']
  653.             self['MIME-Version'] = '1.0'
  654.         
  655.         if not self.has_key(header):
  656.             self[header] = type
  657.             return None
  658.         params = self.get_params(header = header, unquote = requote)
  659.         del self[header]
  660.         self[header] = type
  661.         for p, v in params[1:]:
  662.             self.set_param(p, v, header, requote)
  663.         
  664.  
  665.     
  666.     def get_filename(self, failobj = None):
  667.         """Return the filename associated with the payload if present.
  668.  
  669.         The filename is extracted from the Content-Disposition header's
  670.         `filename' parameter, and it is unquoted.  If that header is missing
  671.         the `filename' parameter, this method falls back to looking for the
  672.         `name' parameter.
  673.         """
  674.         missing = object()
  675.         filename = self.get_param('filename', missing, 'content-disposition')
  676.         if filename is missing:
  677.             filename = self.get_param('name', missing, 'content-disposition')
  678.         
  679.         if filename is missing:
  680.             return failobj
  681.         return utils.collapse_rfc2231_value(filename).strip()
  682.  
  683.     
  684.     def get_boundary(self, failobj = None):
  685.         """Return the boundary associated with the payload if present.
  686.  
  687.         The boundary is extracted from the Content-Type header's `boundary'
  688.         parameter, and it is unquoted.
  689.         """
  690.         missing = object()
  691.         boundary = self.get_param('boundary', missing)
  692.         if boundary is missing:
  693.             return failobj
  694.         return utils.collapse_rfc2231_value(boundary).rstrip()
  695.  
  696.     
  697.     def set_boundary(self, boundary):
  698.         """Set the boundary parameter in Content-Type to 'boundary'.
  699.  
  700.         This is subtly different than deleting the Content-Type header and
  701.         adding a new one with a new boundary parameter via add_header().  The
  702.         main difference is that using the set_boundary() method preserves the
  703.         order of the Content-Type header in the original message.
  704.  
  705.         HeaderParseError is raised if the message has no Content-Type header.
  706.         """
  707.         missing = object()
  708.         params = self._get_params_preserve(missing, 'content-type')
  709.         if params is missing:
  710.             raise errors.HeaderParseError('No Content-Type header found')
  711.         params is missing
  712.         newparams = []
  713.         foundp = False
  714.         for pk, pv in params:
  715.             if pk.lower() == 'boundary':
  716.                 newparams.append(('boundary', '"%s"' % boundary))
  717.                 foundp = True
  718.                 continue
  719.             newparams.append((pk, pv))
  720.         
  721.         if not foundp:
  722.             newparams.append(('boundary', '"%s"' % boundary))
  723.         
  724.         newheaders = []
  725.         for h, v in self._headers:
  726.             if h.lower() == 'content-type':
  727.                 parts = []
  728.                 for k, v in newparams:
  729.                     if v == '':
  730.                         parts.append(k)
  731.                         continue
  732.                     parts.append('%s=%s' % (k, v))
  733.                 
  734.                 newheaders.append((h, SEMISPACE.join(parts)))
  735.                 continue
  736.             newheaders.append((h, v))
  737.         
  738.         self._headers = newheaders
  739.  
  740.     
  741.     def get_content_charset(self, failobj = None):
  742.         '''Return the charset parameter of the Content-Type header.
  743.  
  744.         The returned string is always coerced to lower case.  If there is no
  745.         Content-Type header, or if that header has no charset parameter,
  746.         failobj is returned.
  747.         '''
  748.         missing = object()
  749.         charset = self.get_param('charset', missing)
  750.         charset is missing if charset is missing else charset is missing
  751.         
  752.         try:
  753.             if isinstance(charset, str):
  754.                 charset = unicode(charset, 'us-ascii')
  755.             
  756.             charset = charset.encode('us-ascii')
  757.         except UnicodeError:
  758.             return failobj
  759.  
  760.         return charset.lower()
  761.  
  762.     
  763.     def get_charsets(self, failobj = None):
  764.         '''Return a list containing the charset(s) used in this message.
  765.  
  766.         The returned list of items describes the Content-Type headers\'
  767.         charset parameter for this message and all the subparts in its
  768.         payload.
  769.  
  770.         Each item will either be a string (the value of the charset parameter
  771.         in the Content-Type header of that part) or the value of the
  772.         \'failobj\' parameter (defaults to None), if the part does not have a
  773.         main MIME type of "text", or the charset is not defined.
  774.  
  775.         The list will contain one string for each part of the message, plus
  776.         one for the container message (i.e. self), so that a non-multipart
  777.         message will still return a list of length 1.
  778.         '''
  779.         return [ part.get_content_charset(failobj) for part in self.walk() ]
  780.  
  781.     from email.iterators import walk
  782.  
  783.